package org.jetlinks.pro.things.impl.converter;

import org.jetlinks.core.message.MessageType;
import org.jetlinks.core.message.ThingMessage;
import org.jetlinks.pro.things.ThingMessageConverter;
import org.jetlinks.pro.things.ThingMessageConverterProvider;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Component
public class TemplateThingMessageConverterProvider implements ThingMessageConverterProvider {
    @Override
    public String getId() {
        return "template";
    }

    @Override
    public String getName() {
        return "模版转换";
    }

    @Override
    public Mono<ThingMessageConverter> createConverter(Map<String, Object> configuration) {
        Map<String, Object> template = new HashMap<>(configuration);

        convert(template);

        return Mono.just(new TemplateThingMessageConverter(() -> convert(template),ThingMessageConverter.expression()));
    }

    private ThingMessage convert(Map<String, Object> message) {
        return MessageType
            .convertMessage(message)
            .filter(ThingMessage.class::isInstance)
            .map(ThingMessage.class::cast)
            .orElseThrow(() -> new IllegalArgumentException("illegal message format"));
    }
}
